<template>
  <div class="container">
    <div id="map"></div>
  </div>
</template>

<script>
import "mapbox-gl/dist/mapbox-gl.css";
import mapboxgl from "mapbox-gl"; // or "const mapboxgl = require('mapbox-gl');"
// ES6 导入方式
import turf from "@turf/turf";
import { log } from '@luma.gl/gltools';

export default {
  name: "Vue2MapboxMapTemplate",
  data() {
    return {};
  },

  mounted() {
    this.initMap();
  },

  beforeDestroy() {
    clearInterval(this.interval);
  },

  methods: {
    initMap() {
      mapboxgl.accessToken =
        "pk.eyJ1IjoiY3Vpaml5aW5nIiwiYSI6ImNsZ3QyZjY4ODAxbDEza3BkOTJqbTJvN3gifQ.Ldj9qAFzb5uzcLP-VtFB3A";
      const map = new mapboxgl.Map({
        container: "map",
        style: "mapbox://styles/cuijiying/cll09l2nz007w01picbmj3e1z",
        center: [119.30781234997426, 31.96579093157065],
        zoom: 8,
        projection: "mercator",
      });

      // load事件
      let newFeatures = this.genetorGeoJosn();
      map.on("load", () => {
        map.addSource("dynamic-data", {
          type: "geojson",
          // Use a URL for the value for the `data` property.
          // data: "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson",
          data: newFeatures,
        });

        map.addLayer({
          id: "earthquakes-layer",
          type: "circle",
          source: "dynamic-data",
          paint: {
            "circle-radius": 4,
            "circle-stroke-width": 2,
            "circle-color": "red",
            "circle-stroke-color": "white",
          },
        });

        // 假设从服务端获取最新的点位数据（GeoJSON格式）
        // var newFeatures = this.genetorGeoJosn();

        // // 更新GeoJSON数据的函数
        // var source = map.getSource("dynamic-data");
        // source.setData(newFeatures);

        // this.zoomFilter(map)

        

        //
      });

      map.on("zoom", () => {

        // map.setFilter('earthquakes-layer', ['in', 'type',1 ]);
        // this.zoomFilter(map)

        // let iconFeatures = map.queryRenderedFeatures({
        //   layers: ["earthquakes-layer"],
        // });
        // // const overlappingPoints = []; // 存储重叠点位的二维数组
        // const overlappingPoints = new Set(); // 存储重叠点位的二维数组
        // const threshold = 50; // 屏幕距离阈值，单位为像素 // 将地理坐标转换为屏幕坐标
        // function getScreenCoordinates(coordinates) {
        //   const screenCoordinates = map.project(coordinates);
        //   return [screenCoordinates.x, screenCoordinates.y];
        // }
        // for (let i = 0; i < iconFeatures.length; i++) {
        //   // const overlappingGroup = [iconFeatures[i].id]; // 临时数组，存储与当前点位重叠的其他点位
        //   const overlappingGroup = [iconFeatures[i]]; // 临时数组，存储与当前点位重叠的其他点位
        //   const screenCoordinatesA = getScreenCoordinates(
        //     iconFeatures[i].geometry.coordinates
        //   );
        //   for (let j = i + 1; j < iconFeatures.length; j++) {
        //     const screenCoordinatesB = getScreenCoordinates(
        //       iconFeatures[j].geometry.coordinates
        //     );
        //     const distance = Math.sqrt(
        //       Math.pow(screenCoordinatesA[0] - screenCoordinatesB[0], 2) +
        //         Math.pow(screenCoordinatesA[1] - screenCoordinatesB[1], 2)
        //     );
        //     if (distance < threshold) {
        //       // overlappingGroup.push(iconFeatures[j].id);
        //       overlappingGroup.push(iconFeatures[j]);
        //     }
        //   }
        //   if (overlappingGroup.length > 1) {
        //     // 只有存在重叠才将其添加到结果数组中
        //     let maxType = 0;
        //     let maxFeature;

        //     overlappingGroup.forEach((item) => {
        //       if (item.properties.type >= maxType) {
        //         maxType = item.properties.type;
        //         maxFeature = item;
        //       }
        //     });
        //     maxFeature.properties.cluster = true;
        //     // overlappingPoints.push(maxFeature);
        //     overlappingPoints.add(JSON.stringify(maxFeature));
        //   }
        // }

        // // const iterator = overlappingPoints.values();
        // let arr = Array.from(overlappingPoints);
        // // const firstValue = iterator.next().value;
        // console.log(arr);
        // console.log(JSON.parse(arr[0]));

        // console.log(this.mergeArrays(overlappingPoints));
        // let arrayNum = this.mergeArrays(overlappingPoints);
        // //还原数据
        // let clusterFeature = arrayNum.map(item => {
        //   return item.map((index => {
        //     // newFeatures[index].cluster = 1;
        //     let newFeature =  newFeatures.features.find(i=>i.id==index)
        //     newFeature.properties.cluster = 1
        //     return newFeature
        //   }))
        // })

        // console.log(clusterFeature, "clusterFeature===============");
        // console.log(newFeatures, "原来的newFeatures===============");
      });

      map.on("mousemove", "earthquakes-layer", function (e) {
        // var coordinates = e.features[0].geometry.coordinates.slice();
        // var title = e.features[0].properties.id;
        var title = e.features[0].properties.type;

        console.log(title, "iiiiiiiiiiiiiiiiiiiiiiiii");
      });

      map.on('zoomend', () => {
          console.log('zoomend============');
            // 假设从服务端获取最新的点位数据（GeoJSON格式）
            let newFeatures = this.genetorGeoJosn();
            // 更新GeoJSON数据的函数
            let source = map.getSource("dynamic-data");
            source.setData(newFeatures);
      });

      // idle事件里面不能做图层相关的操作，否则会一直循环执行，慎用

      // let that = this;
      // function updateData(){
      //   // 假设从服务端获取最新的点位数据（GeoJSON格式）
      //   let newFeatures = that.genetorGeoJosn();
      //   // 更新GeoJSON数据的函数
      //   let source = map.getSource("dynamic-data");
      //   source.setData(newFeatures);
      // }

      // map.on('idle', () => {
      //     console.log('idle============');
      //     updateData()
      // });

      // // 监听鼠标移动事件
      // map.on("mousemove", function (e) {
      //   // 获取悬停位置的图层
      //   var features = map.queryRenderedFeatures(e.point);
      //   // 如果有图层被悬停
      //   if (features.length > 0) {
      //     map.getCanvas().style.cursor = "pointer"; // 将鼠标图标更改为指针
      //   } else {
      //     map.getCanvas().style.cursor = ""; // 恢复默认的鼠标图标
      //   }
      // });
    },

    zoomFilter(map){
        let zoomLevel = map.getZoom();

        // 使用 'all' 运算符，要素必须同时满足条件1和条件2
        // map.setFilter('earthquakes-layer', ['all',['!has', 'cluster'],  ['in', 'type', 8 ]]);
        // map.setFilter('earthquakes-layer', ['in', 'type', 1,2]);
        map.setFilter('earthquakes-layer', ['!in', 'type', 1,2]);

        // 使用 'any' 运算符，要素只需满足条件1或条件2之一即可
        // map.setFilter('earthquakes-layer', ['any', ['==', 'property1', value1], ['>', 'property2', value2]]);

        // if (zoomLevel < 5) {
        //   map.setFilter('earthquakes-layer', ['in', 'type',1 ]);
        // } else if ( zoomLevel>=5 && zoomLevel < 9) {
        //   map.setFilter('earthquakes-layer', ['in', 'type',1,2,3]);
        // } else if ( zoomLevel>=9 && zoomLevel < 13) {
        //   map.setFilter('earthquakes-layer', ['in', 'type',1,2,3,4,5,6 ]);
        // } else if ( zoomLevel>=13 && zoomLevel < 16) {
        //   map.setFilter('earthquakes-layer', ['in', 'type',1,2,3,4,5,6,7,8 ]);
        // } else if ( zoomLevel>=16 && zoomLevel < 19) {
        //   map.setFilter('earthquakes-layer', ['in', 'type',1,2,3,4,5,6,7,8,10 ]);
        // } 

    },

    mergeArrays(arrays) {
      const graph = {}; // 图数据结构表示子数组之间的交集关系

      // 构建图的连通性关系
      for (let i = 0; i < arrays.length; i++) {
        const array1 = arrays[i];
        const key1 = String(i);

        // 检查当前子数组是否与其他子数组有交集
        for (let j = i + 1; j < arrays.length; j++) {
          const array2 = arrays[j];
          const key2 = String(j);

          // 检查两个子数组是否有交集
          const hasIntersection = array1.some((value) =>
            array2.includes(value)
          );

          if (hasIntersection) {
            // 添加连通关系到图中
            if (!graph[key1]) {
              graph[key1] = new Set();
            }
            graph[key1].add(key2);

            if (!graph[key2]) {
              graph[key2] = new Set();
            }
            graph[key2].add(key1);
          }
        }
      }

      const mergedArrays = []; // 用于存储合并后的数组
      const visited = new Set(); // 已访问过的子数组的索引

      // 遍历每个子数组，如果没有被访问过，则进行深度优先搜索合并
      for (let i = 0; i < arrays.length; i++) {
        const key = String(i);

        if (!visited.has(key)) {
          const mergedArray = [];
          this.mergeConnectedArrays(key, mergedArray, visited, graph, arrays);
          mergedArrays.push(Array.from(new Set(mergedArray))); // 去除合并后的数组中的重复值
        }
      }

      return mergedArrays;
    },

    // 深度优先搜索（DFS）合并具有连通关系的子数组
    mergeConnectedArrays(key, mergedArray, visited, graph, arrays) {
      mergedArray.push(...arrays[Number(key)]);
      visited.add(key);

      if (graph[key]) {
        for (const neighbor of graph[key]) {
          if (!visited.has(neighbor)) {
            this.mergeConnectedArrays(
              neighbor,
              mergedArray,
              visited,
              graph,
              arrays
            );
          }
        }
      }
    },

    genetorGeoJosn() {
      var geojsonPoints = {
        type: "FeatureCollection",
        features: [],
      };

      // 南京地区的经纬度范围
      var bounds = {
        north: 32.072443,
        south: 31.905137,
        east: 118.601604,
        west: 118.495696,
      };

      // 创建15个随机点位
      for (var i = 0; i < 1000; i++) {
        // var point = createRandomPoint(bounds,i);
        var longitude =
          bounds.west + Math.random() * (bounds.east - bounds.west);
        var latitude =
          bounds.south + Math.random() * (bounds.north - bounds.south);

        geojsonPoints.features.push({
          id: i + 1,
          type: "Feature",
          geometry: {
            type: "Point",
            coordinates: [longitude, latitude],
          },
          properties: {
            id: i + 1,
            type: Math.floor(Math.random() * 10),
          },
        });
      }

      // 打印生成的GeoJSON点位数据
      // console.log(JSON.stringify(geojsonPoints));

      return geojsonPoints;
    }, //
  },
};
</script>

<style></style>
